package com.financing.wap.web.controller.api;



import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.wap.common.Pager;
import com.financing.wap.common.ResultMap;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.common.Session;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.dto.ClientUserBaseDTO;
import com.financing.wap.dto.CorpClientUserBaseDTO;
import com.financing.wap.dto.CorpFaUserDTO;
import com.financing.wap.dto.UserDTO;
import com.financing.wap.service.IClientService;
import com.financing.wap.service.IOrderService;
import com.financing.wap.service.IUserService;
import com.financing.wap.util.Constants;
import com.financing.wap.util.DTOdateSetUtil;
import com.financing.wap.util.RiskAssessQuestionUtil;
import com.financing.wap.vo.OrderVO;
import com.financing.wap.vo.QueryClientUserVo;
import com.financing.wap.web.controller.BaseController;

@Controller("apiClientController")
@RequestMapping("/api/client")
public class ClientController  extends BaseController{

	Logger logger = Logger.getLogger(getClass());

	@Autowired
	private IClientService clientService;

	@Autowired
	private IUserService userService;
	
	@Autowired
	private IOrderService orderService;
	/**
	 * 展示所有客户列表
	 * @return
	 */
	@RequestMapping("/list")
	@ResponseBody
	public ResultMap list(HttpServletRequest request, HttpServletResponse response,QueryClientUserVo queryVo){
		ResultMap result = new ResultMap();

		Session session = SessionUtil.getSession();
		UserDTO loginUser = session.getUser();
		String type = loginUser.getUType();

		if(Constants.FA_TYPE_CORP.equals(type)){

			result = corpList(request,response,queryVo);
		}else{
			result = userList(request,response,queryVo);
		}
		return result;
	}

	/**
	 * 展示客户资料
	 * @return
	 */
	@RequestMapping("/{id}")
	@ResponseBody
	public ResultMap view(@PathVariable int id,HttpServletRequest request, HttpServletResponse response,Integer clientId){

		ResultMap result = new ResultMap();
		try {
			if(clientId!=null && clientId >0){
				id = clientId;
			}
			ClientUserBaseDTO clientUserBaseDTO = clientService.searchClientUserBaseById(id);
			boolean checkResult = checkUserRight(request,response,Integer.valueOf(clientUserBaseDTO.getcPaCode()));
			if(!checkResult){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
				result.setMessage("违规操作，账号权限错误！");
				return result;
			}
			result.setStatus(STATUS.SUCCESS);
			result.setAttribute("dto", clientUserBaseDTO);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		}catch(Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}



	/**
	 * 编辑客户资料
	 * @return
	 */
	@RequestMapping(value="/edit",method=RequestMethod.GET)
	@ResponseBody
	public ResultMap editPost(HttpServletRequest request, HttpServletResponse response,ClientUserBaseDTO clientUserBaseDTO){
		ResultMap result = new ResultMap();
		try {
			Session session = SessionUtil.getSession();
			UserDTO loginUser = session.getUser();
			String type = loginUser.getUType();
			String faId = loginUser.getId();
			
			
			ClientUserBaseDTO checkDTO = clientReNameCheck(faId,clientUserBaseDTO.getcName(),clientUserBaseDTO.getcMobile(),clientUserBaseDTO.getId());
			//重名校验，name+mobile
			if(checkDTO!=null){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_RENAME_ERROE);
				result.setMessage("userName:"+checkDTO.getcName()+"("+checkDTO.getcMobile()+") has been fount! it has reName erro!" );
				return result;
			}
			
			if(Constants.FA_TYPE_CORP.equals(type)){
				QueryClientUserVo vo = new QueryClientUserVo();
				vo.setCorpId(faId);
				vo.setId(clientUserBaseDTO.getId());
				int size = clientService.getClientUserListCount(vo);
				if(size<=0){
					result.setStatus(STATUS.ERROR);
					result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
					result.setMessage("违规操作，账号权限受限！");
					return result;
				}
			}else{
				clientUserBaseDTO.setcPaCode(faId.toString());
				if(!faId.toString().equals(clientUserBaseDTO.getcPaCode())){
					result.setStatus(STATUS.ERROR);
					result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
					result.setMessage("违规操作，账号权限受限！");
					return result;
				}
			}


			clientUserBaseDTO.setcNumberType(1);//默认身份证
			clientUserBaseDTO.setUpdateBy(faId.toString());
			clientService.updateClientUserBase(clientUserBaseDTO);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		} catch (Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
	/**
	 * 新增客户
	 * @return
	 */
	@RequestMapping(value="/add",method=RequestMethod.GET)
	@ResponseBody
	public ResultMap addPost(@Valid ClientUserBaseDTO clientUserBaseDTO,BindingResult validationResult, HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap(); 
		if (validationResult.hasErrors()) {
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_VALIDATE_ERROR);
			result.setMessage("校验不通过！");

			return result;  
		}

		try {
			Session session = SessionUtil.getSession();
			UserDTO loginUser = session.getUser();
			String faId = loginUser.getId();
			clientUserBaseDTO.setcNumberType(1);//默认身份证
			clientUserBaseDTO.setcPaCode(faId.toString());
			clientUserBaseDTO.setCreateBy(faId.toString());
			clientUserBaseDTO.setUpdateBy(faId.toString());

			ClientUserBaseDTO checkDTO = clientReNameCheck(faId,clientUserBaseDTO.getcName(),clientUserBaseDTO.getcMobile(),null);
			if(checkDTO!=null){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_RENAME_ERROE);
				result.setMessage("userName:"+checkDTO.getcName()+"("+checkDTO.getcMobile()+") has been fount! it has reName erro!" );
			}else{
				Integer id = clientService.insertClientUserBase(clientUserBaseDTO);
				result.setAttribute("id", id);
				result.setStatus(STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			}


		} catch (Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

		/**
		 * 删除客户
		 * @return
		 */
		@RequestMapping(value="/delete",method=RequestMethod.GET)
		@ResponseBody
		public ResultMap delete( HttpServletRequest request, HttpServletResponse response,Integer id){
			ResultMap result = new ResultMap();
			try {
				Session session = SessionUtil.getSession();
				UserDTO loginUser = session.getUser();
				String faId = loginUser.getId();

				ClientUserBaseDTO cb = new ClientUserBaseDTO();
				cb.setId(id);
				cb.setcPaCode(String.valueOf(faId));
				
				OrderVO where = new OrderVO();
				where.setClientid(id);
				if(orderService.getOrderListCount(where) <= 0){
					clientService.deleteClient(cb);
					result.setStatus(STATUS.SUCCESS);
					result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				}else{
					result.setStatus(STATUS.FAILE);
					result.setStatusCode(ResultMap.STATUS_CODE_HVAE_ORDER_ERROR);
				}
				
			} catch (Exception e) {
				logger.error("==>error messang:",e);
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			}
			return result;
		}

	/**
	 * 客户重名验证
	 * @param faId
	 * @param cName
	 * @param cMobile
	 * @return
	 */
	private ClientUserBaseDTO clientReNameCheck(String faId,String cName,String cMobile,Integer id){
		QueryClientUserVo queryVo = new QueryClientUserVo();
		queryVo.setFaId(faId);
		queryVo.setcName(cName);
		queryVo.setcMobile(cMobile);
		queryVo.setId(id);
		if(id!=null){
			queryVo.setCheckNameTag("1");
		}
		
		List<ClientUserBaseDTO> list = clientService.getClientUserList(queryVo);
		if(list.size()>0){
			return list.get(0);
		}
		return null;

	}

	/**
	 * 判断登录人的操作权限
	 * @param request
	 * @param response
	 * @param faId 客户所属fa的ID（自由+机构fa）
	 */
	private Boolean checkUserRight(HttpServletRequest request, HttpServletResponse response,Integer faId){
		Session session = SessionUtil.getSession();
		UserDTO loginUser = session.getUser();
		String type = loginUser.getUType();
		String userId = loginUser.getId();

/*		if(Constants.FA_TYPE_CORP.equals(type)){//登陆人为机构账户
			CorpFaUserDTO usreDTO = userService.getUserById(faId);//获取客户所属FA的基本信息
			if(usreDTO.getuManagerId().equals(userId) || faId.equals(userId)){
				return true;
			}
			return false;
		}else{
			if(faId.equals(userId)){
				return true;
			}
			return false;
		}*/
		if(faId.equals(userId)){
			return true;
		}
		return false;
	}


	/**
	 * 展示所有客户列表
	 * @return
	 */
	private  ResultMap userList(HttpServletRequest request, HttpServletResponse response,QueryClientUserVo queryVo){
		ResultMap result = new ResultMap();

		Session session = SessionUtil.getSession();
		UserDTO loginUser = session.getUser();
		String faId = loginUser.getId();

		try {
			queryVo.setFaId(faId);
			Pager pager = new Pager();
			String pageNo = request.getParameter("pageNo");
			if(StringUtils.isBlank(pageNo)){
				pageNo="1";
			}			
			Integer count = clientService.getClientUserListCount(queryVo);
			pager.setTotalCount(count);
			pager.setPageSize(queryVo.getPageSize());
			pager.setPageNo(Integer.parseInt(pageNo));
			queryVo.setStart(pager.getStartIndex());
			List<ClientUserBaseDTO> clientList  = clientService.getClientUserList(queryVo);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("list", clientList);
			result.setAttribute("pager", pager);
		}catch(Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}


	/**
	 * 展示所有客户列表
	 * @return
	 */
	private  ResultMap corpList(HttpServletRequest request, HttpServletResponse response,QueryClientUserVo queryVo){
		ResultMap result = new ResultMap();

		Session session = SessionUtil.getSession();
		UserDTO loginUser = session.getUser();
		String corpId = loginUser.getId();

		try {
			queryVo.setCorpId(corpId);
			Pager pager = new Pager();
			String pageNo = request.getParameter("pageNo");
			if(StringUtils.isBlank(pageNo)){
				pageNo="1";
			}			
			Integer count = clientService.getCorpClientUserListCount(queryVo);
			pager.setTotalCount(count);
			pager.setPageSize(queryVo.getPageSize());
			pager.setPageNo(Integer.parseInt(pageNo));
			queryVo.setStart(pager.getStartIndex());
			List<CorpClientUserBaseDTO> clientList  = clientService.getCorpClientUserList(queryVo);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("list", clientList);
			result.setAttribute("pager", pager);
		}catch(Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
	/**
	 * 获取客户风险评估问卷
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/questionList")
	@ResponseBody
	public ResultMap questionList(HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap();
		try{
			List<Map<Object,Object>> questionPagerList =RiskAssessQuestionUtil.allQuestionsList;
			result.setAttribute("resultJson", questionPagerList);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		}catch(Exception e) {
			logger.error("error questionList messang:",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			result.setMessage("转发失败!");
		}

		return result;
	}
	/**
	 * 添加客户信息 
	 * @return
	 */
	@RequestMapping(value="/addClientAndQuestion")
	@ResponseBody
	public ResultMap addClientAndQuestion( ClientUserBaseDTO clientUserBaseDTO,String qajson, HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap(); 

		try {
			
			Session session = SessionUtil.getSession();
			UserDTO loginUser = session.getUser();
			String faId = loginUser.getId();
			clientUserBaseDTO.setcNumberType(1);//默认身份证
			clientUserBaseDTO.setcPaCode(faId.toString());
			// 初始化属性
			DTOdateSetUtil.setUpdateInfo(clientUserBaseDTO);
			DTOdateSetUtil.setCreateInfo(clientUserBaseDTO);
			//wap_jee_1.4 删除判断 客服重名
			/*			
			//判断客户重名
			ClientUserBaseDTO checkDTO = clientReNameCheck(faId,clientUserBaseDTO.getcName(),clientUserBaseDTO.getcMobile(),null);
			if(checkDTO!=null){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_RENAME_ERROE);
				result.setMessage("userName:"+checkDTO.getcName()+"("+checkDTO.getcMobile()+") has been fount! it has reName erro!" );
				return result;
			}*/
			
			Integer id = clientService.addClientAndQuestion(clientUserBaseDTO,qajson);
			result.setAttribute("id", id);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);


		} catch (Exception e) {
			logger.error("in addClientAndQuestion error messang:",e);
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
}
